package com.xwh.shop.goods.service.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xwh.shop.goods.model.entity.Goods;
import com.xwh.shop.goods.model.vo.GoodsDetailsVO;
import com.xwh.shop.goods.model.vo.GoodsPageVO;
import com.xwh.shop.goods.service.mapper.GoodsMapper;
import com.xwh.shop.goods.service.service.GoodsImageService;
import com.xwh.shop.goods.service.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwh
 * @since 2025-07-16
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

//    1. 用goodsMapper连表查询图片

//    2.用goodsImageService
    @Resource
    private GoodsImageService goodsImageService;

    @Override
    public GoodsDetailsVO findDetailsById(Long goodsId) {
        Goods goods = this.getById(goodsId);
        GoodsDetailsVO goodsDetailsVO = new GoodsDetailsVO();
        BeanUtils.copyProperties(goods, goodsDetailsVO);

        // todo 待补充
        goodsDetailsVO.setSales(0);
        goodsDetailsVO.setImageUrl(goodsImageService.getImagesByGoodsId(goodsId));
        goodsDetailsVO.setTags(List.of("新品","热卖","推荐"));
        return goodsDetailsVO;
    }

    @Override
    public IPage<GoodsPageVO> pageQuery(Integer current, Integer pageSize, String name, Long categoryId, Byte isShow) {
        LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.hasText(name),Goods::getName,name);
        wrapper.eq(categoryId != null,Goods::getCategoryId,categoryId);
        wrapper.eq(isShow != null, Goods::getStatus,isShow);

        Page<Goods> page = this.page(new Page<>(current,pageSize), wrapper);
        IPage<GoodsPageVO> pageVO = new Page<>();
        BeanUtils.copyProperties(page, pageVO);


        List<Goods> goods = page.getRecords();
        List<GoodsPageVO> goodsPageVOList = new ArrayList<>();
        for (Goods good : goods) {
            GoodsPageVO goodsPageVO = new GoodsPageVO();
            BeanUtils.copyProperties(good,goodsPageVO);

            //todo 补充字段
            goodsPageVO.setSales(0);
            goodsPageVO.setImageUrl(goodsImageService.getMainImageByGoodsId(good.getId()));
            goodsPageVO.setTags(List.of("新品","热卖","推荐"));

            goodsPageVOList.add(goodsPageVO);
        }
        pageVO.setRecords(goodsPageVOList);
        return pageVO;
    }
}
